#!/usr/bin/env node
import { Command } from 'commander'
import got from 'got'
import inquirer from 'inquirer'
import { Project, preview } from 'miniprogram-ci'
import path from 'path'
import shell from 'shelljs'
import { buildProject } from '../tools/main'

const program = new Command()

program
  .option('-e --env [env]', '【选填】指定运行环境 默认：--env=uat')
  .option('-d --dir <dir>', '【必填】指定运行项目 示例：--dir=p099')

program.parse(process.argv)

interface Opts {
  env: 'uat' | 'prod' | 'dev'
  dir: string
}

interface Prompt {
  appid: string
  desc: string
}

// 模拟顶层 await
void (async () => {
  const { env = 'uat', dir = '' }: Opts = program.opts()
  if (dir === undefined) return console.log('请检查运行项目的入参')

  const { opt, cmdStr } = buildProject({
    env, dir, runType: 'build'
  })

  const {
    appid = '', desc = ''
  }: Prompt = await inquirer.prompt([{
    type: 'list',
    name: 'appid',
    message: '选择小程序',
    choices: [
      { name: '智慧海鹚', value: 'wx670d0301a227c14c' },
      { name: '海鹚测试2', value: 'wx670d0301a227c14c' }
    ]
  }, {
    type: 'input',
    name: 'desc',
    message: '版本详情：'
  }])

  console.log('获取详情', desc)

  // 打包项目
  if (shell.cd(opt).code !== 0) {
    throw new Error('进入目录错误')
  }
  if (shell.exec(cmdStr).code !== 0) {
    throw new Error('运行打包命令失败')
  }

  const { body: robot } = await got(`http://bmzxn5.preview.laf.run/get-robot-status?appid=${appid}`)
  console.log('robot', robot)

  const cwdDir = process.cwd()
  const type = opt === '' ? 'wepy' : 'taro'
  const projectPath = {
    wepy: path.join(cwdDir, './dist'),
    taro: path.join(cwdDir, `../../dist/${dir}/weapp`)
  }
  const project = new Project({
    appid,
    type: 'miniProgram',
    projectPath: projectPath[type],
    privateKeyPath: path.join(__dirname, `../../key/private.${appid}.key`)
  })
  await preview({
    project,
    version: '2023.01.31.00',
    desc,
    setting: {
      es6: false,
      minify: true
    },
    qrcodeFormat: 'image',
    qrcodeOutputDest: `${cwdDir}/destination.jpg`,
    onProgressUpdate: console.log
  })
})()
